const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser'); // 导入koa-bodyparser
const { name } = require('ejs');

const app = new Koa();
const router = new Router();

// 使用bodyParser中间件解析请求体
app.use(bodyParser());

// 定义路由
router.get('/', async (ctx) => {
  ctx.body = 'Welcome to the home page!';
});

router.get('/about', async (ctx) => {
  ctx.body = 'This is the about page.';
});

router.post('/submit', async (ctx) => {
  const data = ctx.request.body; // 获取请求体数据
  console.log("获得请求体数据>>>>",data);

//   ctx.body = `Received data: ${JSON.stringify(data)}`;
  ctx.body = data;
});

// 新增http方法
let obj={
    name:'zhangsan',
    age:18
}
router.put('/update', async (ctx) => {
  const data = ctx.request.body;
  console.log("获得请求体数据>>>>",data);
//   比如将obj的name和age更新为请求体的name和age
  obj.name=data.name;
  obj.age=data.age
  ctx.body = obj;
});
// 使用路由中间件
app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});